<!-- 公益事项 -->
<template>
  <div id="login">
    <!-- 搜索框 -->
    <div class="search">
      <myFrom v-bind="formConfig" v-model:formData="formData">
        <template #header>
          <Title>
            <template #title>搜索</template>
          </Title>
        </template>
        <template #footer>
          <div class="footer">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </div>
        </template>
      </myFrom>
    </div>
    <!-- 表单 -->
    <div class="mytable">
      <myTable
        :tableData="tableData"
        v-bind="tableConfig"
        v-model:pageList="pageList"
      >
        <template #header>
          <Title>
            <template #title> 登录日志列表 </template>
          </Title>
        </template>
        <template #time="scope">
          {{ relativeTime(scope.row.time) }}
        </template>
        <template #name="scope">
          <template v-if="scope.row.author?.name">
            {{ scope.row.author?.name }}
          </template>
          <template v-else> 该管理员已注销 </template>
        </template>
        <template #avatar="scope">
          <el-image
            style="width: 50px; height: 50px"
            :src="baseURL + scope.row.author?.avatar"
            :preview-src-list="[baseURL + scope.row.author?.avatar]"
            fit="cover"
            lazy
            :z-index="99999"
          />
        </template>
        <template #operation="scope">
          <div class="operation">
            <el-button
              type="danger"
              :icon="Delete"
              circle
              @click="handleDelete(scope.row._id)"
            />
          </div>
        </template>
        <template #equipment="scope">
          {{ conversionEquipment(scope.row.equipment) }}
        </template>
      </myTable>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

import myFrom from '@/base-ui/form'
import myTable from '@/base-ui/table'
import { Title } from '@/components/admin/public'

import { formConfig, tableConfig } from '@/views/admin/config/login.config'

import { getAdmintorList } from '@/server/serve/api_admintor'
import {
  journalListData,
  searchloginJournal,
  deleteJournal
} from '@/server/serve/api_journal'
import type { JournalListDataTypes } from '@/server/serve/api_journal'

import { baseURL } from '@/utils/axios'

import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'

import { relativeTime } from '@/utils/date-time'
import conversionEquipment from '@/utils/conversion-equipment'

// 初始化数据 表单
const formDataInitial: any = {}
for (const key of formConfig.formItems) {
  formDataInitial[`${key.field}`] = ''
  if (key.field === 'equipment') {
    formDataInitial[`${key.field}`] = 3
  }
}
// 搜索表单数据
const formData = ref<any>(formDataInitial)

// 表格分页数据
const pageList = ref({
  // 当前页数
  currentPage: 1,
  // 当前页显示数据条数
  pageSize: 10,
  // 条数列表
  pageSizes: [5, 10, 15, 20],
  // 总数
  total: 0
})

// 表格信息
const tableData = ref<any>()

// 监听表格数据展示方式，是否为默认 搜索数据
const defaultDataShowType = ref<boolean>(true)

// 数据初始化
const dataInitialization = async () => {
  // 默认表格数据
  if (defaultDataShowType.value) {
    journalListData(
      0,
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    ).then(({ data: listData }) => {
      tableData.value = listData.data
        ?.journalList as Array<JournalListDataTypes>
      pageList.value.total = listData.data?.allNums as number
    })
  }
  // 搜索表格数据
  else {
    const { name, time, equipment } = formData.value
    if (!name)
      return ElMessage({
        type: 'warning',
        message: '请选择用户'
      })
    const startTime = new Date(time[0]).getTime()
    const endTime = new Date(time[1]).getTime()
    const { data: searchList } = await searchloginJournal(
      formData.value.name,
      startTime,
      endTime,
      equipment,
      pageList.value.pageSize,
      (pageList.value.currentPage - 1) * pageList.value.pageSize
    )
    if (searchList.code)
      return ElMessage({
        type: 'warning',
        message: searchList.mes
      })
    tableData.value = searchList.data?.journalList
    pageList.value.total = searchList.data?.allNums as number
  }
}

// 监听分页改变
watch(
  pageList,
  () => {
    dataInitialization()
  },
  { deep: true, immediate: true }
)

// 获取管理员列表
getAdmintorList().then(({ data }) => {
  let adminList: any = []
  data.data?.admintorList.forEach((item) => {
    adminList.push({
      value: item._id,
      label: item.name
    })
  })
  formConfig.formItems.map((item) => {
    if (item.field === 'name') {
      return (item.selectOptions = adminList)
    }
  })
})

// 搜索按钮触发
const handleSearch = () => {
  defaultDataShowType.value = false
  dataInitialization()
}

// 删除日志
const handleDelete = (journalID: string) => {
  ElMessageBox.confirm('确认删除该日志信息吗?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      const { data: deleteInfo } = await deleteJournal(journalID)
      if (deleteInfo.code)
        return ElMessage({
          type: 'warning',
          message: deleteInfo.mes
        })

      // 本地缓存 提升性能
      const findIndex = tableData.value.findIndex(
        (item: any) => item._id === journalID
      )
      tableData.value.splice(findIndex, 1)

      ElMessage({
        type: 'success',
        message: deleteInfo.mes
      })
    })
    .catch(() => {
      console.log()
    })
}
</script>

<style scoped lang="less">
#login {
  .search {
    border-radius: 16px;
    background-color: #fff;
    padding: 0 20px;
    .footer {
      display: flex;
      justify-content: flex-end;
      padding: 10px 30px;
    }
  }
  .mytable {
    border-radius: 16px;
    margin-top: 20px;
    padding: 20px;
    background-color: #fff;
  }
}
</style>
